import React, { useState, useEffect } from "react";
import "./app.less";
import logo from "../public/icon.jpg";
import axios from "axios";

// 弹窗宽度
const MODAL_WIDTH = 350;
/**
 * 边界检测，鼠标点击modal之外，modal隐藏
 * @param {*} x 鼠标的x轴位置
 * @param {*} y 鼠标的y轴位置
 * @param {*} modalPosition 弹窗的left和top
 */
const boundaryDetection = (x, y, modalPosition = { left: 0, top: 0 }) => {
  let { left, top } = modalPosition;
  if (
    x > left &&
    x < left + MODAL_WIDTH &&
    y > top &&
    y < top + MoveSearchApp.offsetHeight
  ) {
    return true;
  }
  return false;
};

const computeModalPosition = (selectionObj = window.getSelection()) => {
  // 获取选中文字的位置，x y是横纵坐标，height width是选中文字的
  const { x, y, width, height } = selectionObj
    .getRangeAt(0)
    .getBoundingClientRect();

  // 计算弹窗位置，算出left和top
  let left = x - MODAL_WIDTH / 2 + width / 2;
  left = left > 10 ? left : 10;
  let top = y + height;
  // 左侧滚动距离
  const scrollLeft =
    document.documentElement.scrollLeft || document.body.scrollLeft;
  // 上下滚动距离
  const scrollTop =
    document.documentElement.scrollTop || document.body.scrollTop;
  return {
    left: left + scrollLeft,
    top: top + scrollTop
  };
};

export default function App() {
  const [show, setShow] = useState(false);
  const [selectText, setSelectText] = useState("");
  const [dataSource, setDataSource] = useState([]);
  const [modalPosition, setModalPosition] = useState({
    left: 0,
    top: 0
  });

  useEffect(() => {
    const mouseupHandle = async e => {
      const selectionObj = window.getSelection();
      const selectedText = selectionObj.toString();
      setSelectText(selectedText);

      if (selectedText) {
        setModalPosition(computeModalPosition(selectionObj));
        const url = `https://movesearch.vercel.app/api/baidu?query=${selectedText}&pageNum=1&pageSize=10`;
        const res = await axios.get(url);
        const data = res.data.data.documents.data || [];
        setDataSource(data);
        setShow(!!data.length);
      } else if (show) {
        // 重新计算是否关闭弹窗
        // 检测鼠标位置是否在弹窗内，不是则关闭弹窗
        if (!boundaryDetection(e.clientX, e.pageY, modalPosition)) {
          setDataSource([]);
          setShow(false);
        }
      }
    };
    window.addEventListener("mouseup", mouseupHandle);
    return () => {
      window.removeEventListener("mouseup", mouseupHandle);
    };
  });
  return show && dataSource && dataSource.length ? (
    <div
      className="move-search"
      id="MoveSearchApp"
      style={{
        ...modalPosition
      }}>
      <div className="move-search-content">
        <ul className="move-search-ul">
          {dataSource.map(l => (
            <li className="move-search-li" key={l.id}>
              <a href={l.url} target="_blank">
                {l.title}
              </a>
              <span>{l.summary}</span>
            </li>
          ))}
        </ul>
      </div>
      <div className="move-search-bottom-fade"></div>
      <footer className="move-search-footer">
        <a
          href={`https://kaifa.baidu.com/searchPage?wd=${selectText}`}
          target="_blank">
          Read More
        </a>
      </footer>
    </div>
  ) : null;
}
